import { EventEmitter } from 'events';
import { DatabaseService } from '../database/DatabaseService';
import { createModuleLogger } from '../../utils/logger';

const logger = createModuleLogger('config-service');

export interface DynamicConfig {
  monitoring: {
    minTransactionValue: number;
    maxTransactionsPerBlock: number;
    blockCheckInterval: number;
  };
  chains: {
    ethereum: { rpcUrl: string };
    bsc: { rpcUrl: string };
    base: { rpcUrl: string };
    bitcoin: { apiUrl: string };
    solana: { rpcUrl: string };
  };
  alerts: {
    email: {
      enabled: boolean;
      host: string;
      port: number;
      user?: string;
      password?: string;
    };
    webhook: {
      enabled: boolean;
      url?: string;
    };
  };
}

export class ConfigService extends EventEmitter {
  private static instance: ConfigService;
  private config: DynamicConfig;
  private dbService: DatabaseService;
  private refreshInterval: NodeJS.Timeout | null = null;
  private lastUpdateTime: Date = new Date();

  private constructor(dbService: DatabaseService) {
    super();
    this.dbService = dbService;
    this.config = this.getDefaultConfig();
  }

  public static getInstance(dbService: DatabaseService): ConfigService {
    if (!ConfigService.instance) {
      ConfigService.instance = new ConfigService(dbService);
    }
    return ConfigService.instance;
  }

  // 获取默认配置
  private getDefaultConfig(): DynamicConfig {
    return {
      monitoring: {
        minTransactionValue: 50000,
        maxTransactionsPerBlock: 20,
        blockCheckInterval: 15000
      },
      chains: {
        ethereum: { rpcUrl: 'https://ethereum.publicnode.com' },
        bsc: { rpcUrl: 'https://bsc-dataseed1.binance.org' },
        base: { rpcUrl: 'https://mainnet.base.org' },
        bitcoin: { apiUrl: 'https://blockstream.info/api' },
        solana: { rpcUrl: 'https://api.mainnet-beta.solana.com' }
      },
      alerts: {
        email: {
          enabled: false,
          host: 'smtp.gmail.com',
          port: 587
        },
        webhook: {
          enabled: false
        }
      }
    };
  }

  // 初始化配置服务
  public async initialize(): Promise<void> {
    try {
      // 从数据库加载配置
      await this.loadFromDatabase();
      
      // 启动定期刷新
      this.startPeriodicRefresh();
      
      logger.info('配置服务初始化完成');
    } catch (error) {
      logger.error('配置服务初始化失败:', error);
      // 使用默认配置
      this.config = this.getDefaultConfig();
      logger.warn('使用默认配置');
    }
  }

  // 从数据库加载配置
  private async loadFromDatabase(): Promise<void> {
    try {
      const allConfigs = await this.dbService.getAllConfigs();
      
      // 解析配置到结构化对象
      const newConfig = this.getDefaultConfig();
      
      // 监控配置
      if (allConfigs['monitoring.minTransactionValue']) {
        newConfig.monitoring.minTransactionValue = allConfigs['monitoring.minTransactionValue'].value;
      }
      if (allConfigs['monitoring.maxTransactionsPerBlock']) {
        newConfig.monitoring.maxTransactionsPerBlock = allConfigs['monitoring.maxTransactionsPerBlock'].value;
      }
      if (allConfigs['monitoring.blockCheckInterval']) {
        newConfig.monitoring.blockCheckInterval = allConfigs['monitoring.blockCheckInterval'].value;
      }

      // 链配置
      if (allConfigs['chains.ethereum.rpcUrl']) {
        newConfig.chains.ethereum.rpcUrl = allConfigs['chains.ethereum.rpcUrl'].value;
      }
      if (allConfigs['chains.bsc.rpcUrl']) {
        newConfig.chains.bsc.rpcUrl = allConfigs['chains.bsc.rpcUrl'].value;
      }
      if (allConfigs['chains.base.rpcUrl']) {
        newConfig.chains.base.rpcUrl = allConfigs['chains.base.rpcUrl'].value;
      }
      if (allConfigs['chains.bitcoin.apiUrl']) {
        newConfig.chains.bitcoin.apiUrl = allConfigs['chains.bitcoin.apiUrl'].value;
      }
      if (allConfigs['chains.solana.rpcUrl']) {
        newConfig.chains.solana.rpcUrl = allConfigs['chains.solana.rpcUrl'].value;
      }

      // 告警配置
      if (allConfigs['alerts.email.enabled']) {
        newConfig.alerts.email.enabled = allConfigs['alerts.email.enabled'].value;
      }
      if (allConfigs['alerts.email.host']) {
        newConfig.alerts.email.host = allConfigs['alerts.email.host'].value;
      }
      if (allConfigs['alerts.email.port']) {
        newConfig.alerts.email.port = allConfigs['alerts.email.port'].value;
      }
      if (allConfigs['alerts.webhook.enabled']) {
        newConfig.alerts.webhook.enabled = allConfigs['alerts.webhook.enabled'].value;
      }

      // 检查配置是否有变化
      const hasChanges = JSON.stringify(this.config) !== JSON.stringify(newConfig);
      
      if (hasChanges) {
        const oldConfig = { ...this.config };
        this.config = newConfig;
        this.lastUpdateTime = new Date();
        
        logger.info('配置已更新');
        this.emit('configChanged', {
          oldConfig,
          newConfig: this.config,
          timestamp: this.lastUpdateTime
        });
      }

    } catch (error) {
      logger.error('从数据库加载配置失败:', error);
      throw error;
    }
  }

  // 启动定期刷新
  private startPeriodicRefresh(): void {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }

    // 每30秒检查一次配置更新
    this.refreshInterval = setInterval(async () => {
      try {
        await this.loadFromDatabase();
      } catch (error) {
        logger.error('定期刷新配置失败:', error);
      }
    }, 30000);

    logger.info('配置定期刷新已启动 (30秒间隔)');
  }

  // 获取当前配置
  public getConfig(): DynamicConfig {
    return { ...this.config };
  }

  // 获取监控配置
  public getMonitoringConfig() {
    return { ...this.config.monitoring };
  }

  // 获取链配置
  public getChainConfig(chain: string) {
    return this.config.chains[chain as keyof typeof this.config.chains];
  }

  // 获取告警配置
  public getAlertsConfig() {
    return { ...this.config.alerts };
  }

  // 更新配置
  public async updateConfig(updates: Partial<DynamicConfig>): Promise<void> {
    try {
      const configUpdates: Record<string, any> = {};

      // 处理监控配置更新
      if (updates.monitoring) {
        if (updates.monitoring.minTransactionValue !== undefined) {
          configUpdates['monitoring.minTransactionValue'] = updates.monitoring.minTransactionValue;
        }
        if (updates.monitoring.maxTransactionsPerBlock !== undefined) {
          configUpdates['monitoring.maxTransactionsPerBlock'] = updates.monitoring.maxTransactionsPerBlock;
        }
        if (updates.monitoring.blockCheckInterval !== undefined) {
          configUpdates['monitoring.blockCheckInterval'] = updates.monitoring.blockCheckInterval;
        }
      }

      // 处理链配置更新
      if (updates.chains) {
        Object.entries(updates.chains).forEach(([chain, config]) => {
          if (chain === 'bitcoin') {
            // Bitcoin使用apiUrl
            if ((config as any).apiUrl !== undefined) {
              configUpdates[`chains.${chain}.apiUrl`] = (config as any).apiUrl;
            }
          } else {
            // 其他链使用rpcUrl
            if ((config as any).rpcUrl !== undefined) {
              configUpdates[`chains.${chain}.rpcUrl`] = (config as any).rpcUrl;
            }
          }
        });
      }

      // 处理告警配置更新
      if (updates.alerts) {
        if (updates.alerts.email) {
          Object.entries(updates.alerts.email).forEach(([key, value]) => {
            if (value !== undefined) {
              configUpdates[`alerts.email.${key}`] = value;
            }
          });
        }
        if (updates.alerts.webhook) {
          Object.entries(updates.alerts.webhook).forEach(([key, value]) => {
            if (value !== undefined) {
              configUpdates[`alerts.webhook.${key}`] = value;
            }
          });
        }
      }

      // 批量更新到数据库
      if (Object.keys(configUpdates).length > 0) {
        await this.dbService.setConfigs(configUpdates);
        
        // 立即重新加载配置
        await this.loadFromDatabase();
        
        logger.info('配置更新完成');
      }

    } catch (error) {
      logger.error('更新配置失败:', error);
      throw error;
    }
  }

  // 重置为默认配置
  public async resetToDefault(): Promise<void> {
    const defaultConfig = this.getDefaultConfig();
    await this.updateConfig(defaultConfig);
    logger.info('配置已重置为默认值');
  }

  // 获取配置更新时间
  public getLastUpdateTime(): Date {
    return this.lastUpdateTime;
  }

  // 停止服务
  public stop(): void {
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
      this.refreshInterval = null;
    }
    logger.info('配置服务已停止');
  }
} 